package org.xnat.xnatfs.webdav;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.bradmcevoy.http.LockInfo;
import com.bradmcevoy.http.LockResult;
import com.bradmcevoy.http.LockTimeout;
import com.bradmcevoy.http.LockToken;

public class LockManager {

  /**
   * maps current locks by the file associated with the resource
   */

  Map<String, LockToken> locks;
  public static final Logger logger = Logger.getLogger ( LockManager.class );

  public LockManager () {
    locks = new HashMap<String, LockToken> ();
  }

  public synchronized LockResult lock ( LockTimeout timeout, LockInfo lockInfo, VirtualResource resource ) {
    logger.debug ( "lock called for " + resource.getAbsolutePath () );
    LockToken currentLock = locks.get ( resource );
    if ( currentLock != null ) {
      return LockResult.failed ( LockResult.FailureReason.ALREADY_LOCKED );
    }
    LockToken newToken = new LockToken ( resource.getAbsoluteName (), lockInfo, timeout );
    locks.put ( newToken.tokenId, newToken );
    return LockResult.success ( newToken );
  }

  public synchronized LockResult refresh ( String tokenId, VirtualResource resource ) {
    logger.debug ( "refresh called for " + resource.getAbsolutePath () );
    LockToken currentLock = locks.get ( resource );
    currentLock.setFrom ( new Date () );
    return LockResult.success ( currentLock );
  }

  public synchronized void unlock ( String tokenId, VirtualResource resource ) {
    logger.debug ( "unlock called for " + resource.getAbsolutePath () );
    LockToken token = locks.get ( resource );
    if ( token != null ) {
      locks.remove ( token.tokenId );
    }
  }

}
